package com.miniserver.util;

/**
 * 字符串格式化工具类
 * 
 * @author PC
 * 
 */
public class StringFormatUtil {
	private static final Character kongge = 32; // 空格
	private static final Character huiche = 13; // 回车
	private static final Character huanhang = 10; // 换行

	/**
	 * 替换字符串中特殊字符
	 */
	public static String formatString2XML(String strData) {
		if (strData == null) {
			return "";
		}
		strData = replaceString(strData, "&", "&amp;");
		strData = replaceString(strData, "<", "&lt;");
		strData = replaceString(strData, ">", "&gt;");
		strData = replaceString(strData, "&apos;", "&apos;");
		strData = replaceString(strData, "\"", "&quot;");
		return strData;
	}

	/**
	 * 还原字符串中特殊字符
	 */
	public static String formatStringXML2String(String strData) {
		strData = replaceString(strData, "&lt;", "<");
		strData = replaceString(strData, "&gt;", ">");
		strData = replaceString(strData, "&apos;", "&apos;");
		strData = replaceString(strData, "&quot;", "\"");
		strData = replaceString(strData, "&amp;", "&");
		return strData;
	}

	/**
	 * 处理JSON中的特殊字符
	 */
	public static String convertToJsonString(String str) {
		if (str == null) {
			return "";
		} else {
			return str.replace("\\", "\\\\").replace("\"", "\\\"")
					/*.replace("'", "\\\'")*/.replace("\r", "\\r")
					.replace("\n", "\\n").replace("\t", "\\t")
					.replace("\b", "\\b");
		}
	}

	/**
	 * 处理JSON中的特殊字符
	 */
	public static String convertToSqlString(String str) {
		return str.replace("'", "''");
	}

	/**
	 * 替换一个字符串中的某些指定字符
	 * 
	 * @param strData
	 *            String 原始字符串
	 * @param regex
	 *            String 要替换的字符串
	 * @param replacement
	 *            String 替代字符串
	 * @return String 替换后的字符串
	 */
	public static String replaceString(String strData, String regex, String replacement) {
		if (strData == null) {
			return null;
		}
		int index;
		index = strData.indexOf(regex);
		String strNew = "";
		if (index >= 0) {
			while (index >= 0) {
				strNew += strData.substring(0, index) + replacement;
				strData = strData.substring(index + regex.length());
				index = strData.indexOf(regex);
			}
			strNew += strData;
			return strNew;
		}
		return strData;
	}

	/**
	 * 字符串转html格式
	 * 
	 * @param str
	 * @return
	 */
	public static String jsstr2html(String str) {
		return content2html(jsstr2content(str));
	}

	/**
	 * 去掉\
	 * 
	 * @param str
	 * @return
	 */
	public static String jsstr2content(String str) {
		return str == null ? "" : str.replace("\\r", huiche.toString()).replace("\\n", huanhang.toString())
				.replace("\\\"", "\"").replace("\\'", "'");
	}

	/**
	 * 将特殊符号转为html格式
	 * 
	 * @param content
	 * @return
	 */
	public static String content2html(String content) {
		return content.replace("&", "&amp;").replace(kongge.toString(), "&nbsp;").replace("<", "&lt;")
				.replace(">", "&gt;").replace("\"", "&quot;").replace(huiche.toString() + huanhang.toString(), "<br/>")
				.replace(huiche.toString(), "<br/>").replace(huanhang.toString(), "<br/>");
	}
}